<?php

namespace app\admin\controller\order;
use app\admin\model\Cart;
use app\admin\model\OrderLog;
use app\admin\model\Express;
use app\admin\model\User;
use app\common\controller\Backend;

/**
 * 
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\Order
     */
    protected object $model;
    protected array $withJoinTable = ['user'=>['nickname','avatar','id']];
    protected string|array $defaultSortField = 'oid,desc';

    protected array|string $preExcludeFields = ['create_time'];

    protected string|array $quickSearchField = ['oid', 'ordernum', 'user_id', 'uname', 'tel', 'address', 'tradernum'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Order();
    }



    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

     /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $where[] = ['order.shop_id','=',$this->store_id];
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $arr = $res->items();
        $oids = array_column($arr,"oid");
        if($oids){
             $order_cart = [];
             $carts = Cart::whereIn("guan_oid",$oids)->select();
             foreach($carts as &$v){
                  $order_cart[$v['guan_oid']][] = $v;
             }
        }
        foreach($arr as &$v){
              $v['cart'] = $order_cart[$v['oid']] ?? [];
              $v['order_money'] = ['shi_money'=>$v['shi_money'],'money'=>$v['money'],'hui'=>$v['hui']];
              $v['order_info'] =  ['ordernum'=>$v['ordernum'],'uname'=>$v['uname'],'tel'=>$v['tel'],'address'=>'address','remarks'=>$v['remarks'],'orderdes'=>$v['orderdes'],'tradernum'=>$v['tradernum'],'order_types'=>order_t($v['types'])];
              $v['order_s'] = ['status'=>$v['is_pay'],'order_status'=>$v['order_status']];
              $v['all_time'] = ['create_time'=>date("Y-m-d H:i:s",$v['creat_time']),'pay_time'=>date("Y-m-d H:i:s",$v['pay_time']),'complete_time'=>$v['complete_time'],'deliver_time'=>$v['deliver_time'],'receive_time'=>$v['receive_time']];
               
        }

        $this->success('', [
            'list'   => $arr,
            'total'  => $res->total(),
            'remark' => get_route_remark(),
            'where'=>$where
        ]);
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function details($id): void
    {
         
        $res = $this->model->alias("o")->join("user u","o.user_id=u.id","LEFT")->where("o.oid",$id)->field("o.*,u.nickname")->find();
        $res['os'] =order_status_tag($res);
        $res['create_time'] = date("Y-m-d H:i:s",$res['create_time']);
        $cart = Cart::where("guan_oid",$id)->select();
        $log = OrderLog::where("oid",$id)->order("time asc")->select();
        
        $this->success('', [
            'data'   => $res,
            'cart'   =>$cart,
            'log'=>$log
        ]);
        
    }

      /**
     * 获取快递公司
     * @throws Throwable
     */
    public function getExpress(): void
    {
         
        $express = Express::select();
        $this->success('', [
            'list'   => $express
        ]);
        
    }


    function handleOrder(){
           $type = input("post.type");
           $data = input("post.data");
           $find =  $this->model->where("oid",$data['oid'])->find();
           switch ($type) {
               case 'fahuo':
                   if($find['is_pay'] == 1 && $find['order_status']==9){
                        $this->success('ok',['code'=>100,'msg'=>'订单已完成，无需发货！']);exit;
                   }
                   $res = $this->model->where("oid",$data['oid'])->update([
                        'logistics_company'=>$data['logistics_company'],
                        'logistics_no'=>$data['logistics_no']
                   ]);
                   $log = '订单发货，快递公司ID：'.$data['logistics_company'].'，快递单号：'.$data['logistics_no'];
                   break;
               case 'beizhu':
                    $res = $this->model->where("oid",$data['oid'])->update([
                        'orderdes'=>$data['orderdes']
                    ]);
                    $log = '订单备注：'.$data['orderdes'];
                    break;
                case 'change_price':
                    $res = $this->model->where("oid",$data['oid'])->update([
                        'money'=>$data['money']
                    ]);
                    $log = '订单金额修改：'.$data['money'];
                    break;
               case 'change_ps':
                    $res = $this->model->where("oid",$data['oid'])->update([
                        'pay_style'=>$data['pay_style']
                    ]);
                    $log = '订单支付方式修改：'.$data['pay_style'];
                    break;
               case 'tuikuan':
                    if($find['is_pay'] == 1 && $find['order_status']==8){
                        $this->success('ok',['code'=>100,'msg'=>'订单已退款，无需重复退款！']);exit;
                    }
                    $res = $this->model->where("oid",$data['oid'])->update([
                        'order_status'=>8
                    ]);
                    $log = '订单退款成功';
                    break;
               default:
                   // code...
                   break;
           }
           if($res){

              OrderLog::insert([
                    'log'=>$log,
                    'time'=>date("Y-m-d H:i:s"),
                    'oid'=>$data['oid']
              ]);
              $this->success('ok',$res);
           }else{
              $this->success('ok',['code'=>100,'msg'=>'操作失败']);exit;
           }
           
    }

    //订单统计
    function getOrderStatics(){
            $order_sales = [
                'date'=>['06.10','06.11','06.12','06.13','06.14','06.15','06.16','06.17','06.18','06.19'],
                'n'=>[23,665,23,765,980,1212,43,678,123,564]
            ];

            $date_arr = [];
            $money_arr = [];
            $d = date("Y-m-d");
            for($i=0;$i<15;$i++){   
                  
                  $date=date("Y-m-d", strtotime("-".$i." day $d"));
                  $date_arr[] = $date;
                  $stime = strtotime($date." 00:00:00");
                  $etime = strtotime($date." 23:59:59");
                  $w=array();
                  $w['create_time'] = [$stime,$etime];
                  $w['is_pay']=1;
                  $smoney = $this->model->where($w)->sum("money");
                  $money_arr[] = $smoney ?? 0;
             }
             $latest_day = ['money'=>$money_arr,'date'=>$date_arr];
             
             $tong['order_sum'] = $this->model->where(['is_pay'=>1])->count();
             $tong['order_sum_money'] = $this->model->where(['is_pay'=>1])->sum("money");
             $tong['user_sum'] = User::count();
             $tong['user_sum_pay'] = $this->model->where(['is_pay'=>1])->group("user_id")->count();
             $tong['order_tui'] = $this->model->where(['is_pay'=>1,'order_status'=>7])->field("oid")->count();
             $tong['order_daifa'] = $this->model->where(['is_pay'=>1,'order_status'=>0])->field("oid")->count();
             $tong['order_tuied'] = $this->model->where(['is_pay'=>1,'order_status'=>8])->field("oid")->count();
             $tong['order_success'] = $this->model->where(['is_pay'=>1,'order_status'=>9])->field("oid")->count();
             $this->success('ok',['order_sales'=>$order_sales,'latest_day'=>$latest_day,'tong'=>$tong]);
    }

    //获取订单状态参数
    function getOs(){
           $res = [
                ['name'=>'待付款','os'=>0],
                ['name'=>'待发货','os'=>1],
                ['name'=>'待收货','os'=>2],
                ['name'=>'申请退款','os'=>7],
                ['name'=>'已退款','os'=>8],
                ['name'=>'交易完成','os'=>9],

           ];
           $this->success("ok",['list'=>$res]);
    }

}